package me.leiusual.sharing.ui.account

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_account_login.*
import me.leiusual.sharing.R
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.MainViewModel
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.util.extension.toast
import timber.log.Timber
import javax.inject.Inject

/**
 * Create by leiusual on 2018/7/16
 */
class AccountLoginFragment : DaggerFragment() {

  companion object {
    const val USERNAME = "username"
    const val PASSWORD = "password"
  }

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val mainViewModel: MainViewModel by activityViewModels { factory }

  private val viewModel: AccountLoginViewModel by viewModels { factory }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_account_login, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    bindData()

    // 记住账号
    edit_text_username.setText(viewModel.user.username)

    text_view_register.setOnClickListener {
      findNavController().navigate(R.id.action_accountLoginFragment_to_accountRegisterFragment)
    }

    text_view_forget.setOnClickListener {
      findNavController().navigate(R.id.action_accountLoginFragment_to_accountForgetFragment)
    }

    button_login.setOnClickListener {
      val username = edit_text_username.text.toString()
      val password = edit_text_password.text.toString()
      viewModel.accessToken(username, password)
    }

    observeData()
  }

  private fun bindData() {
    val username = arguments?.getString(USERNAME) ?: return
    val password = arguments?.getString(PASSWORD) ?: return
    edit_text_username.setText(username)
    edit_text_password.setText(password)
  }

  private fun observeData() {
    viewModel.accessToken.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("accessToken = %s", it)
      when (it) {
        is Data.Loading -> {
          button_login.isEnabled = false
        }
        is Data.Error -> {
          button_login.isEnabled = true
          toast(it.error.message)
        }
        is Data.Success -> {

          // 登录成功，清除临时选中数据
          mainViewModel.address(null)
          mainViewModel.bank(null)

          // 返回
          findNavController().popBackStack()
        }
      }
    })
  }
}